from flask import Blueprint, jsonify, render_template, request
from ..models import HostMachineInfo, Snapshot, UserContainerLink
from ..services.svc_snapshots import get_snapshots as svc_get_snapshots
from ..services.svc_dev_envs import get_all_containers

bp_snapshots = Blueprint("snapshots", __name__, url_prefix="/snapshots")


# 获取所有开发环境
@bp_snapshots.route("/get_dev_envs", methods=["GET"])
def get_dev_envs():
    snapshots_with_distinct_dev_env_name = Snapshot.query.distinct(
        Snapshot.dev_env_name
    ).all()
    devenv_names = [
        snapshot.dev_env_name for snapshot in snapshots_with_distinct_dev_env_name
    ]
    # 去重
    devenv_names = list(set(devenv_names))

    return jsonify([{"name": devenv_name} for devenv_name in devenv_names])


# 新增路由以渲染
@bp_snapshots.route("/view", methods=["GET"])
def view_hosts():
    return render_template("snapshots.html")


# 新增 get_snapshots 接口
# 可以获取全部快照
@bp_snapshots.route("/get_snapshots", methods=["GET"])
def get_snapshots():
    dev_env_name = request.args.get("dev_env_name")
    if not dev_env_name:
        return jsonify({"error": "dev_env_name is required"}), 400

    snapshots = svc_get_snapshots(dev_env_name)
    return jsonify(
        [
            {
                "id": snapshot.id,
                "base_image": snapshot.base_image,
                "snapshot_image": snapshot.snapshot_image,
            }
            for snapshot in snapshots
        ]
    )


# 新增 get_snapshots 接口
# 可以获取开发环境下的全部快照和容器
@bp_snapshots.route("/get_snapshots_and_containers", methods=["GET"])
def get_snapshots_and_containers():
    dev_env_name = request.args.get("dev_env_name")
    if not dev_env_name:
        return jsonify({"error": "dev_env_name is required"}), 400

    snapshots = svc_get_snapshots(dev_env_name)
    containers = get_all_containers(dev_env_name)
    return jsonify(
        {
            "snapshots": [
                {
                    "id": snapshot.id,
                    "base_image": snapshot.base_image,
                    "snapshot_image": snapshot.snapshot_image,
                }
                for snapshot in snapshots
            ],
            "containers": containers,
        }
    )
